import { bindRigidBodyToNode } from 'XrFrame/kanata/lib/index';
import { baseUrl as BASE_URL, timeout as TIMEOUT} from '../api/config'

export interface RequestConfig {
  url:string,
  method:HttpRequestMethod,
  data?:any,
  header?:HttpRequestHeader
  contentType?:string,
  token?:boolean
}

interface HttpRequestHeader{
  Authorization?:string,
  // 'content-type': 'application/json' // 默认值
  'content-type'?:string
}

interface WxHttpResponse{
  code:number,
  msg:string,
  data:any
}

export interface LengyuHttpResponse{
  code:number,
  msg:string,
  data:any
}
export const LENGYU_SUCCESS_CODE:number=20000;

export enum HttpRequestMethod {
	GET = "GET",
	POST = "POST",
};

export interface PageRequestParam{
  pageIndex:number;
  pageSize:number;
  paramMapObj?:JSON;
}


// let httpMethod = getHttpMethod("get"); // 正确
// httpMethod = getHttpMethod("customMethod".toLowerCase()); 

/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function request(body:RequestConfig):Promise<LengyuHttpResponse>{

  let url = BASE_URL + body.url;
  let data = body.data;
  let method = body.method;
  let emptyHeader:HttpRequestHeader ={}
  let header = body.header ? body.header : emptyHeader;
    wx.showLoading({
        title: "加载中",
        mask: true  //开启蒙版遮罩
    });
    if(body.token){
      header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
    }
    if(body.contentType){
      header['content-type'] = body.contentType;
    }

  
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.request({
            url: url,
            timeout: TIMEOUT,
            method: method,
            data: data,
            header: header,
            success: (res) => {
                // if (res.data && res.data.code == 401) {
                //     // 跳转登录
                //     reject(res.data);
                //     wx.navigateTo({
                //       url: '/pages/login/login',
                //     })
                // }
                //微信的回调出发Promise的回调
                wx.hideLoading();
                resolve(res.data as LengyuHttpResponse);
            },
            fail: (res) => {
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            }
        })
    })
}


/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function download(body:RequestConfig):Promise<WechatMiniprogram.DownloadFileSuccessCallbackResult>{
  let url =  body.url;
    wx.showLoading({
        title: "加载中",
        mask: true  //开启蒙版遮罩
    });
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.downloadFile({
            url: url,
            timeout: TIMEOUT,
            success: (res) => {
                //微信的回调出发Promise的回调
                // resolve(res.data as LengyuHttpResponse);
                 // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  resolve(res)
                }
            },
            fail: (res) => {
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            },
          
        })
    })
}



/**
 * 请求封装
 * @param body
 * @returns {Promise<unknown>}
 */
export function upload(body:RequestConfig,filePath:string
                        ):Promise<LengyuHttpResponse>{
    let url = BASE_URL + body.url;
    wx.showLoading({
        title: "加载中",
        mask: true  //开启蒙版遮罩
    });
    let emptyHeader:HttpRequestHeader ={}
    let header = body.header ? body.header : emptyHeader;
    if(body.token){
      header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
    }
    //返回Promise对象
    return new Promise((resolve, reject)=> {
        wx.uploadFile({
            url: url,
            timeout: TIMEOUT,
            filePath: filePath,
            name: 'file',
            header: header,
            formData: body.data,
            success: (res) => {
                //微信的回调出发Promise的回调
                // resolve(res.data as LengyuHttpResponse);
                 // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  const result: LengyuHttpResponse = <LengyuHttpResponse>JSON.parse(res.data);
                  resolve(result);
                }
            },
            fail: (res) => {
                wx.showToast({
                    title: res.errMsg,
                    icon: 'error',
                    duration: 2000
                })
                reject(res);
            },
            complete: () => {
                wx.hideLoading();
            }
        })
    })
}